//
//  SelectProductController.m
//  FactorySale
//
//  Created by 主事丫环HU on 2020/7/25.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "SelectProductController.h"
#import "SelectProdectHeaderView.h"
#import "SelectProductCell.h"
#import "SelectProductModel.h"
#import "CreateSendOrderController.h"
//通过类对象来生成nib
#define NibWithClass(Class)  [UINib nibWithNibName:NSStringFromClass([Class class]) bundle:nil]
//通过类对象生成string
#define StringWithClass(Class) NSStringFromClass([Class class])

@interface SelectProductController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *sectionDataArray;// 存放区中返回行数的数组
@property (nonatomic,strong) NSMutableArray *sectionModelArray;// 给区头赋值
@property (nonatomic,strong) NSMutableArray *isExpandArray;// 存储展开闭合状态的数组
@property (nonatomic,strong) NSMutableArray *selectedArray;// 已选择的数组
@end

@implementation SelectProductController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.sectionDataArray = [NSMutableArray arrayWithCapacity:0];
    self.sectionModelArray = [NSMutableArray arrayWithCapacity:0];
    self.isExpandArray = [NSMutableArray arrayWithCapacity:0];
    self.selectedArray = [NSMutableArray arrayWithCapacity:0];
    [self requestCooperativeProductsListData];
}
- (void)requestCooperativeProductsListData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"attributes"] = @"";
    [NetWorkTool POST:getPartsByFactory param:param success:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        self.sectionModelArray = [SelectProductModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        
        NSArray * dataArray = dic[@"data"];
        for (int i = 0; i <dataArray.count; i++) {
            NSDictionary * listDic = dataArray[i];
            NSArray *attributeListArray = listDic[@"attributeList"];
            NSMutableArray *rowModelArray = [SelectProductListModel mj_objectArrayWithKeyValuesArray:attributeListArray];
            [self.sectionDataArray addObject:rowModelArray];
        }
        
        for (int i = 0; i<self.sectionModelArray.count; i++) {
            [self.isExpandArray addObject:@"0"];//0:没展开 1:展开
        }
        [self.tableView reloadData];
        
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        
    } needUser:YES];
}
- (void)setupUI{
    self.title = @"合作产品";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    
    [self.rightbutton setTitle:@"全选" forState:(UIControlStateNormal)];
    [self.rightbutton setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:(UIControlStateNormal)];
    self.rightbutton.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [self.rightbutton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.view.backgroundColor = Main_BackGroundColor;
    
    [self.tableView registerNib:NibWithClass(SelectProdectHeaderView) forHeaderFooterViewReuseIdentifier:StringWithClass(SelectProdectHeaderView)];
    self.tableView.rowHeight = 90;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
}
#pragma mark - tableview delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.sectionModelArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SelectProductModel *model = self.sectionModelArray[section];
    SelectProdectHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:StringWithClass(SelectProdectHeaderView)];
    headerView.model = model;
    if ([self.isExpandArray[section] isEqualToString:@"0"]) {
        //未展开
        [headerView.expandButton setImage:[UIImage imageNamed:@"向下"] forState:UIControlStateNormal];
    }else{
        //展开
        [headerView.expandButton setImage:[UIImage imageNamed:@"向上"] forState:UIControlStateNormal];
    }
    headerView.expandButton.tag = section;
    [headerView.expandButton addTarget:self action:@selector(expandButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    //这个tag记录分区
    headerView.selectButton.tag = section;
    [headerView.selectButton addTarget:self action:@selector(selectSectionPartsButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    return headerView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    footerView.backgroundColor = Main_BackGroundColor;
    return footerView;
}
#pragma mark - tableview datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    NSMutableArray * rowListArray = self.sectionDataArray[section];
    if ([self.isExpandArray[section]isEqualToString:@"1"]) {
        return rowListArray.count;
    }else{
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SelectProductCell *cell = [SelectProductCell cellWithTableView:tableView];
    cell.model = self.sectionDataArray[indexPath.section][indexPath.row];
    [cell.selectOneButton addTarget:self action:@selector(selectOneGoodsButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
// 全选按钮
- (void)rightButtonClick:(UIButton *)sender{
    [self.selectedArray removeAllObjects];
    sender.selected = !sender.selected;
    
    //每个分区的选中按钮
    for (int i = 0; i < self.sectionModelArray.count; i++) {
        SelectProductModel *sectionModel = self.sectionModelArray[i];
        sectionModel.isSelected = sender.selected;
    
        NSArray *rowModelArray = self.sectionDataArray[i];
        //每一行的选中按钮
        for (int j = 0; j < rowModelArray.count; j++) {
            SelectProductListModel *model = rowModelArray[j];
            model.isSelected = sender.selected;
            if (model.isSelected == YES) {
                [self.selectedArray addObject:model];
            } else {
                [self.selectedArray removeObject:model];
            }
        }
    }
    [self.tableView reloadData];
}
// 区头选择按钮
- (void)selectSectionPartsButtonClicked:(UIButton *)sender{
    sender.selected = !sender.selected;
    SelectProductModel *sectionModel = self.sectionModelArray[sender.tag];
    sectionModel.isSelected = sender.selected;
    NSArray *rowModelArray = self.sectionDataArray[sender.tag];
    //该分区中每一行的按钮
    for (int i = 0; i < rowModelArray.count; i++) {
        SelectProductListModel *rowModel = rowModelArray[i];
        rowModel.isSelected = sender.selected;
        if (rowModel.isSelected == YES) {
            [self.selectedArray addObject:rowModel];
        } else {
            [self.selectedArray removeObject:rowModel];
        }
    }
    [self.tableView reloadData];
}
// cell选择按钮
- (void)selectOneGoodsButtonClicked:(UIButton *)sender{
    sender.selected = !sender.selected;
    //该行的选择按钮
    SelectProductCell *productCell = (SelectProductCell *)[[sender superview]superview];
    NSIndexPath *indexPathForCell = [self.tableView indexPathForCell:productCell];
    
    NSArray *rowModelArray = self.sectionDataArray[indexPathForCell.section];
    SelectProductListModel *currentScp = rowModelArray[indexPathForCell.row];
    currentScp.isSelected = sender.selected;
    
    if (currentScp.isSelected == YES) {
        [self.selectedArray addObject:currentScp];
    } else {
        [self.selectedArray removeObject:currentScp];
    }
    
    SelectProductModel *sccp = self.sectionModelArray[indexPathForCell.section];
    //根据该分区中每一行的选中按钮，得出是否要选中该分区
    for (int i = 0; i < rowModelArray.count; i++) {
        SelectProductListModel *scp = rowModelArray[i];
        if (scp.isSelected == NO) {
            sccp.isSelected = NO;
            break;
        }
        //如果分区中每行都被选中了，那么该分区才被选中
        if (i == rowModelArray.count - 1) {
            sccp.isSelected = YES;
        }
        
    }
    [self.tableView reloadData];
}

- (void)expandButtonClick:(UIButton *)sender{
    if ([self.isExpandArray[sender.tag] isEqualToString:@"0"]) {
        //关闭 => 展开
           [_isExpandArray replaceObjectAtIndex:sender.tag withObject:@"1"];
    }else{
        //展开 => 关闭
           [_isExpandArray replaceObjectAtIndex:sender.tag withObject:@"0"];
    }
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:sender.tag];
    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
}
- (IBAction)confirmButtonClick:(UIButton *)sender {
    if (self.selectedArray.count == 0) {
        ShowToastWithText(@"请选择合作产品");
        return;
    }
    CreateSendOrderController * vc = [[CreateSendOrderController alloc] init];
    vc.model = self.model;
    vc.modelArray = [self.selectedArray mutableCopy];
    [self.navigationController pushViewController:vc animated:YES];
}


@end
